package cn.com.anysdk.ocr.monitor;

import cn.com.anysdk.ocr.exception.OcrException;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * OCR 监控管理器
 */
@Slf4j
public class OcrMonitorManager {
    private static final OcrMonitorManager INSTANCE = new OcrMonitorManager();
    private final List<OcrMonitorListener> listeners = new CopyOnWriteArrayList<>();

    private OcrMonitorManager() {
    }

    /**
     * 获取实例
     */
    public static OcrMonitorManager getInstance() {
        return INSTANCE;
    }

    /**
     * 添加监听器
     */
    public void addListener(OcrMonitorListener listener) {
        if (listener != null) {
            listeners.add(listener);
        }
    }

    /**
     * 移除监听器
     */
    public void removeListener(OcrMonitorListener listener) {
        if (listener != null) {
            listeners.remove(listener);
        }
    }

    /**
     * 通知监听器
     */
    public void notifyListeners(OcrException exception, OcrOperationContext context) {
        if (exception == null || context == null) {
            return;
        }

        for (OcrMonitorListener listener : listeners) {
            try {
                listener.onOcrException(exception, context);
            } catch (Exception e) {
                log.error("Failed to notify OCR monitor listener", e);
            }
        }
    }

    /**
     * 清空监听器
     */
    public void clearListeners() {
        listeners.clear();
    }
}